package com.xavier.utils;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    private static RedisTemplate redisTemplate;

    public static final String REDIS_PREFIX = "xavier:";

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }

    private static String getRealKey(String key) {
        if (!key.contains(REDIS_PREFIX)) {
            return REDIS_PREFIX + key;
        }
        return key;
    }

    /**
     * 根据key查询
     *
     * @param key
     * @return
     */
    public static String get(String key) {
        if (StrUtil.isEmpty(key)) {
            return null;
        }
        Object object = redisTemplate.opsForValue().get(getRealKey(key));
        return Objects.isNull(object) ? null : object.toString();
    }

    public static String leftPop(String key) {
        if (StrUtil.isEmpty(key)) {
            return null;
        }
        Object object = redisTemplate.opsForList().leftPop(getRealKey(key));
        return Objects.isNull(object) ? null : object.toString();
    }

    /**
     * 根据key设置值，并附加过期时间
     *
     * @param key
     * @param value
     * @param unit    时间单位
     * @param timeout 超时时间
     */
    public static void set(String key, Object value, TimeUnit unit, long timeout) {
        if (StrUtil.isEmpty(key)) {
            return;
        }
        key = getRealKey(key);
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public static void set(String key, List<String> valueList, TimeUnit unit, long timeout) {
        if (StrUtil.isEmpty(key)) {
            return;
        }
        key = getRealKey(key);
        redisTemplate.opsForList().rightPushAll(key, valueList);
        redisTemplate.expire(key, timeout, unit);
    }

    public static void set(String key, List<String> valueList) {
        if (StrUtil.isEmpty(key)) {
            return;
        }
        key = getRealKey(key);
        redisTemplate.opsForList().rightPushAll(key, valueList);
    }

    /**
     * 根据key重新设置过期时间
     *
     * @param key
     * @param unit    时间单位
     * @param timeout 超时时间
     */
    public static void expire(String key, TimeUnit unit, long timeout) {
        if (StrUtil.isEmpty(key)) {
            return;
        }
        key = getRealKey(key);
        redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 删除
     *
     * @param key
     */
    public static void delete(String key) {
        if (StrUtil.isEmpty(key)) {
            return;
        }
        key = getRealKey(key);
        redisTemplate.delete(key);
    }


}
